package com.zhiqianbao.activity;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.User;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.ValidateUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.util.HashMap;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

import static com.zhiqianbao.utils.Constants.SMS_CODE_TOKEN;

/**
 * Created by liang on 2015/12/29.
 */
public class VerificationPhoneActivity extends BaseActivity {
    /**
     * 原手机号
     */
    EditText editTextOldTelNum;
    /**
     * 短信验证码
     */
    EditText edittextSmsAuthCode;
    /**
     * 短信验证码获取按钮
     */
    Button buttonObtainSmsAuthCode;
    /**
     * 确认按钮
     */
    Button buttonConfirm;

    //图形验证码
    ImageView loginCode;
    MaterialEditText edittextCode;
    /**
     * 计时器
     */
    TimeCount timeCount;
    private Gson gson = new Gson();

    Handler loginCodeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED :
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Bitmap codeImage = (Bitmap) msg.obj;
                    loginCode.setImageBitmap(codeImage);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verfication_phone);
        init();
        initView();
        gitImageCode();
        getSmsToken();//添加网关验证，防止smsToken过期，过期时间一天
    }

    private void initView() {
         editTextOldTelNum=(EditText)findViewById(R.id.editText_old_tel_num);
         edittextSmsAuthCode=(EditText)findViewById(R.id.edittext_sms_auth_code);
         buttonObtainSmsAuthCode=(Button)findViewById(R.id.button_obtain_sms_auth_code);
         buttonConfirm=(Button)findViewById(R.id.button_confirm);
         loginCode=(ImageView)findViewById(R.id.login_code);
         edittextCode=(MaterialEditText)findViewById(R.id.edittext_code);

        timeCount = new TimeCount(60000, 1000);
        ButtonListener listener = new ButtonListener();
        editTextOldTelNum.setText(Constants.LOGIN_USER.getPhone());
        buttonObtainSmsAuthCode.setOnClickListener(listener);
        buttonConfirm.setOnClickListener(listener);
        loginCode.setOnClickListener(listener);
    }

    private class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            String phoneOld = editTextOldTelNum.getText().toString();
            String code = edittextCode.getText().toString();
            String smsCode=edittextSmsAuthCode.getText().toString().trim();
            if(R.id.button_obtain_sms_auth_code==v.getId()) {
                    if (TextUtils.isEmpty(edittextCode.getText().toString().trim())) {
                        showShortToast1("请输入图片验证码!");
                        return;
                    }
                    //调用发送验证码接口
                    Map<String, String> param = new HashMap<>();
                    param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    param.put("phone", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getPhone().toString() + "" : "");
                    param.put("smstoken", Constants.SMS_CODE_TOKEN);
                    param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    param.put("uuid", Constants.UUID);
                    param.put("code", edittextCode.getText().toString().trim());
                    new CodeAsyncTask().execute(param);
            }
            else if(R.id.login_code==v.getId()) {
                gitImageCode();
            }
            else if(R.id.button_confirm==v.getId()) {
                    if (StringUtils.isBlank(phoneOld)) {
                        showShortToast1("请输入原手机号");
                        return;
                    }
                    if (!ValidateUtils.isMobile(phoneOld)) {
                        showShortToast1("原手机号格式不正确");
                        return;
                    }
                    if (StringUtils.isBlank(code)) {
                        showShortToast1("请输入图形验证码");
                        return;
                    }

                    if (StringUtils.isBlank(smsCode)) {
                        showShortToast1("请输入手机验证码");
                        return;
                    }
                    //调用修改手机号接口
                    Map<String, String> p = new HashMap<>();
                    p.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    p.put("phone", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getPhone().toString()+ "" : "");
                    p.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    p.put("code", edittextSmsAuthCode.getText().toString().trim());
                    new ChangePhoneAsyncTask().execute(p);
            }
        }
    }

    private void gitImageCode() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                String uuid = Constants.UUID;
                Bitmap bitmap = HttpUtils.getUrlImage(Constants.API_ROOT + "/basic/code", VerificationPhoneActivity.this);

                if (null == bitmap) {
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    message.obj = bitmap;
                }
                loginCodeHandler.sendMessage(message);
            }
        }).start();
    }

    //获得请求短信网关接口的 凭证
    private void getSmsToken() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<>();
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/basic/getSmsToken", params, VerificationPhoneActivity.this);
                Message message = new Message();
                if (StringUtils.isBlank(result)) {
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    Result<String> data = Result.fromJson(result, String.class);
                    message.obj = data;
                }
                smsTokenHandler.sendMessage(message);
            }
        }).start();
    }

    Handler smsTokenHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK:
                    Result<String> data = (Result<String>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            SMS_CODE_TOKEN = data.getData();
                            Log.i("SMS_CODE_TOKEN", "SMS_CODE_TOKEN : " + data.getData());
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
        }
    };
    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onTick(long millisUntilFinished) {
            buttonObtainSmsAuthCode.setClickable(false);
            buttonObtainSmsAuthCode.setText(millisUntilFinished / 1000 + "s后重新获取");
        }
        @Override
        public void onFinish() {
            buttonObtainSmsAuthCode.setText("重新获取");
            buttonObtainSmsAuthCode.setClickable(true);
        }
    }

    private class CodeAsyncTask extends AsyncTask<Map, Void, Result<HashMap>> {
        @Override
        protected Result<HashMap> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/phone/code", params[0], VerificationPhoneActivity.this);
            Result<HashMap> resultObject = gson.fromJson(result, Result.class);
            return resultObject;
        }

        @Override
        protected void onPostExecute(Result result) {
            if (result != null) {
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    timeCount.start();
                } else {
                    gitImageCode();
                    showShortToast1(result.getMsg());
                }
            }
        }
    }
    private class ChangePhoneAsyncTask extends AsyncTask<Map, Void, Result<User>> {
        @Override
        protected void onPreExecute() {
            showWaitDialog();
        }
        @Override
        protected Result<User> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/code/check", params[0], VerificationPhoneActivity.this);
            Result<User> resultObject = gson.fromJson(result, Result.class);
            return resultObject;
        }
        @Override
        protected void onPostExecute(Result result) {
            closeWaitDialog();
            if (result != null) {
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                    showShortToast1("验证成功");
                    finish();
                } else {
                    gitImageCode();
                    showShortToast1(result.getMsg());
                }
            }
            else{
                showShortToast1("网络超时，请再试!");
            }
        }
    }

}
